package com.nzw.service.impl.code;

import com.nzw.common.cache.CacheType;
import com.nzw.dao.data.TSysCodeDao;
import com.nzw.pojo.data.TSysCode;
import com.nzw.redis.impl.common.RedisTemplate;
import com.nzw.service.code.CodeService;
import com.nzw.service.impl.common.BaseServiceImpl;
import com.nzw.utils.ValidUtils;
import com.nzw.vo.common.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * Created by XuZhansi on 2017/8/2.
 */
@Service
public class CodeServiceImpl extends BaseServiceImpl implements CodeService {

    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    TSysCodeDao tSysCodeDao;

    @Transactional
    @Override
    public String generateSysCode(int target) {

        TSysCode mfSysCode =tSysCodeDao.getLastCode();
        int code = 0;
        switch (target) {
            case CodeService.MEMBER_CODE:
                code = Integer.parseInt(mfSysCode.getUserCode());
                mfSysCode.setUserCode(String.valueOf(++code));
                break;
        }
        saveOrUpdateEntity(mfSysCode);
        return String.valueOf(code);
    }

    @Override
    public boolean generateMobileCode(CacheType cacheType, String mobile) {
        if (!ValidUtils.isValidMobile(mobile))
            return false;
        /*List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("templateid", "3084009"));
        nvps.add(new BasicNameValuePair("mobile", mobile));
        nvps.add(new BasicNameValuePair("codeLen", "4"));
        String result = HttpUtils.getResultEntityByFormData(Constant.NETEASE_SEND_SMS_CODE + "/sendcode.action", netEase.generateFormHeaders(), nvps, HttpUtils.POST);
        JSONObject jsonObject = JSON.parseObject(result);
        if (jsonObject.getIntValue("code") != 200)
            return false;
        String code = jsonObject.getString("obj");
        switch (cacheType) {
            case USER_CHANGE_PWD_CACHE://修改密码
                redisTemplate.setex(cacheType.getName() + ":" + mobile, 600, code);//有效期10分钟
                break;
            case USER_MOBILE_VERIFY_CACHE://手机号码验证
                redisTemplate.setex(cacheType.getName() + ":" + mobile, 600, code);//有效期10分钟
                break;
        }*/
        return true;
    }


    



    
    /**
     * 验证码
     * @author Administrator
     * @param
     * @autor
     */
    @Override
    public boolean verifyMobileCode(CacheType cacheType, String mobile, Integer code) {
        if (!ValidUtils.isValidMobile(mobile))
            return false;
        String realCode =  redisTemplate.get(cacheType.getName() + ":" + mobile);
        if (realCode == null)
            return false;
        return Integer.parseInt(realCode) == code.intValue();
    }

    public HttpResult getCode(){

        return  new HttpResult(HttpResult.OK,tSysCodeDao.getLastCode());
    }
}
